﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Drawing.Design;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using Kugar.Core.BaseStruct;

namespace Kugar.UI.WinForm
{
    public class ControlListUITypeDesign : UITypeEditor
    {
        /// <summary>
        /// 获取由 EditValue 方法使用的编辑器样式
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
        {
            if (context != null && context.Instance != null)
            {
                return UITypeEditorEditStyle.Modal;
            }
            return base.GetEditStyle(context);
        }

        /// <summary>
        /// 使用指定的服务提供程序和上下文编辑指定对象的值。
        /// </summary>
        /// <param name="context">可用于获取附加上下文信息的 ITypeDescriptorContext。</param>
        /// <param name="provider">IServiceProvider，通过它可能获得编辑服务。</param>
        /// <param name="value">正在编辑的值的实例。</param>
        /// <returns>新的对象值。如果该对象的值尚未更改，则这应返回与传递给它的对象相同的对象</returns>
        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            //为 UITypeEditor 提供一个接口，用于显示 Windows 窗体，或者在设计模式下在属性网格控件的下拉区域中显示控件。
            IWindowsFormsEditorService iws = (IWindowsFormsEditorService)provider.GetService(
                typeof(IWindowsFormsEditorService));

            if (iws != null)
            {
                var valuelist = (Collection<Control>)value;

                using (var UIControl = new ControlListEditor(valuelist, (Control)context.Instance))
                {
                    if (iws.ShowDialog(UIControl) == DialogResult.OK)
                    {
                        valuelist.Clear();

                        foreach (var control in UIControl.Value)
                        {
                            valuelist.Add(control);
                        }

                        context.OnComponentChanged();
                    }
                }
            }
            return value;
        }
    }
}
